package cn.stylefeng.guns.modular.gridsystem.utils;


import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.core.io.FileUtil;
import cn.stylefeng.guns.core.context.constant.ConstantContextHolder;
import cn.stylefeng.guns.sys.modular.timer.tasks.SystemOutTaskRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ssy
 * @date 2022/3/31 9:41
 */
public class MyFileUtils {

    private static Logger logger = LoggerFactory.getLogger(MyFileUtils.class);

    /**
     * 获取上传路径
     *
     * @return
     */
    public static String getUploadPath() {
        //动态获取环境变量的值；Windows 10
        String property = System.getProperties().getProperty("os.name");

        //获取音频文件
        String path;
        if (property.contains("Windows")) {
            path = ConstantContextHolder.getDefaultFileUploadPathForWindows();
        } else {
            path = ConstantContextHolder.getDefaultFileUploadPathForLinux();
        }
        return path;
    }

    /**
     * @param contents 二进制数据
     * @param filePath 文件存放目录，包括文件名及其后缀，如D:\file\bike.jpg
     * @Title: byteToFile
     * @Description: 把二进制数据转成指定后缀名的文件，例如PDF，PNG等
     */
    public static void byteToFile(byte[] contents, String filePath) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream output = null;
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(contents);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            // 获取文件的父路径字符串
            File path = file.getParentFile();
            if (!path.exists()) {
                logger.info("文件夹不存在，创建。path={}", path);
                boolean isCreated = path.mkdirs();
                if (!isCreated) {
                    logger.error("创建文件夹失败，path={}", path);
                }
            }
            fos = new FileOutputStream(file);
            // 实例化OutputString 对象
            output = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                output.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            output.flush();
        } catch (Exception e) {
            logger.error("输出文件流时抛异常，filePath={}", filePath, e);
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (IOException e0) {
                logger.error("文件处理失败，filePath={}", filePath, e0);
            }
        }
    }

    /**
     * 删除指定路径下N天的 .wav文件
     *
     * @param path
     * @param days
     * @param isDelwav
     */
    public static void loopFiles(String path, int days, boolean isDelwav) {
        // 获取目录下的所有【文件】
        List<File> files = FileUtil.loopFiles(path);
        for (File file : files) {
            // N天前的毫秒数
            long threshold1 = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
            logger.info("N天前的时间 >> " + getFormatDate(threshold1));
            //文件最后修改的时间毫秒数
            long threshold2 = file.lastModified();
            logger.info("当前文件的时间 >> " + getFormatDate(threshold2));
            if (threshold2 < threshold1) {
                //判断只删除 .wav文件
                if (isDelwav) {
                    if (file.getAbsolutePath().endsWith(".wav")) {
                        file.delete();
                        //System.out.println(">>> wav 删除成功！");
                    }
                } else {
                    file.delete();
                }
            }
        }
    }

    /**
     * 毫秒转成 时间格式
     *
     * @param timeMillis
     * @return
     */
    public static String getFormatDate(long timeMillis) {
        //   timeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(new Date(timeMillis));
        //System.out.println(timeMillis + " >> " + formattedDate);
        return formattedDate;
    }

    public static void main(String[] args) {
        //getFormatDate(System.currentTimeMillis() - (1 * 24 * 60 * 60 * 1000));
        loopFiles("D:\\tmp\\wav", 1, false);
    }
}
